﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using wicpowerTcpTool.Models;

namespace wicpowerTcpTool
{
    /// <summary>
    /// TCP转发工具主窗口
    /// </summary>
    public partial class MainWindow : Window
    {
        // 存储所有转发组
        private List<ForwardGroup> forwardGroups;

        /// <summary>
        /// 构造函数
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            forwardGroups = new List<ForwardGroup>();
        }

        /// <summary>
        /// 添加转发组按钮点击事件处理
        /// </summary>
        private async void OnAddForwardGroup(object sender, RoutedEventArgs e)
        {
            btnAdd.IsEnabled = false;
            try
            {
                // 验证端口输入并保存所有输入值
                if (!int.TryParse(txtPort1.Text, out int port1) || 
                    !int.TryParse(txtPort2.Text, out int port2))
                {
                    MessageBox.Show("请输入有效的端口号！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 保存当前输入值，避免在后台线程中访问UI控件
                string remark = txtRemark.Text;
                int nextId = forwardGroups.Count + 1;

                // 检查端口是否可用
                bool canStart = await Task.Run(() =>
                {
                    if (!ForwardGroup.IsPortAvailable(port1))
                    {
                        MessageBox.Show($"监听端口 {port1} 已被占用", "错误", 
                            MessageBoxButton.OK, MessageBoxImage.Error);
                        return false;
                    }

                    if (!ForwardGroup.IsPortAvailable(port2))
                    {
                        MessageBox.Show($"转发端口 {port2} 已被占用", "错误", 
                            MessageBoxButton.OK, MessageBoxImage.Error);
                        return false;
                    }

                    return true;
                });

                if (!canStart)
                {
                    return;
                }

                // 创建新的转发组
                var newGroup = new ForwardGroup(nextId, port1, port2, remark);
                
                // 启动转发服务
                try
                {
                    await Task.Run(() => newGroup.Start());
                    
                    // 在UI线程中更新界面
                    await Dispatcher.InvokeAsync(() =>
                    {
                        try
                        {
                            // 添加到列表
                            forwardGroups.Add(newGroup);

                            // 创建并添加UI控件
                            var groupControl = CreateForwardGroupControl(newGroup);
                            forwardGroupsPanel.Children.Add(groupControl);
                            
                            // 清空输入框
                            txtPort1.Text = "";
                            txtPort2.Text = "";
                            txtRemark.Text = "";
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"更新界面时出错: {ex.Message}", "错误", 
                                MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"启动转发服务失败：{ex.Message}", "错误", 
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            finally
            {
                btnAdd.IsEnabled = true;
            }
        }

        /// <summary>
        /// 创建转发组的UI控件
        /// </summary>
        /// <param name="group">转发组对象</param>
        /// <returns>转发组UI控件</returns>
        private UIElement CreateForwardGroupControl(ForwardGroup group)
        {
            // 创建边框容器
            var border = new Border
            {
                BorderBrush = Brushes.LightGray,
                BorderThickness = new Thickness(1),
                Margin = new Thickness(0, 0, 0, 5),  // 只保留底部间距
                Padding = new Thickness(10),
                Background = Brushes.White,
                CornerRadius = new CornerRadius(3)  // 添加圆角
            };

            // 创建网格布局
            var grid = new Grid();
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            // 创建状态面板
            var statusPanel = new StackPanel 
            { 
                Orientation = Orientation.Horizontal,
                Margin = new Thickness(0)
            };
            
            // 服务器1状态指示器
            var server1Status = new Ellipse 
            { 
                Width = 12, 
                Height = 12, 
                Fill = Brushes.Red,
                Margin = new Thickness(5, 0, 5, 0),
                VerticalAlignment = VerticalAlignment.Center
            };
            
            // 服务器2状态指示器
            var server2Status = new Ellipse 
            { 
                Width = 12, 
                Height = 12, 
                Fill = Brushes.Red,
                Margin = new Thickness(5, 0, 5, 0),
                VerticalAlignment = VerticalAlignment.Center
            };
            
            // 数据流指示器
            var dataIndicator = new Ellipse 
            { 
                Width = 12, 
                Height = 12, 
                Fill = Brushes.Gray,
                Margin = new Thickness(5, 0, 5, 0),
                VerticalAlignment = VerticalAlignment.Center
            };

            // 转发组信息标签
            var infoLabel = new TextBlock
            {
                Text = $"序号: {group.Id} | 监听端口: {group.Port1} | 转发端口: {group.Port2} | 备注: {group.Remark}",
                VerticalAlignment = VerticalAlignment.Center,
                TextWrapping = TextWrapping.NoWrap  // 不换行
            };

            // 添加状态指示器和标签到面板
            statusPanel.Children.Add(new TextBlock 
            { 
                Text = "服务1:", 
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 5, 0)
            });
            statusPanel.Children.Add(server1Status);
            statusPanel.Children.Add(new TextBlock 
            { 
                Text = "服务2:", 
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(10, 0, 5, 0)
            });
            statusPanel.Children.Add(server2Status);
            statusPanel.Children.Add(new TextBlock 
            { 
                Text = "数据流:", 
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(10, 0, 5, 0)
            });
            statusPanel.Children.Add(dataIndicator);
            statusPanel.Children.Add(infoLabel);

            // 创建停止按钮
            var stopButton = new Button
            {
                Content = "停止",
                Padding = new Thickness(15, 5, 15, 5),
                Margin = new Thickness(5, 0, 5, 0),
                Height = 28,
                Background = Brushes.White,
                BorderBrush = Brushes.Gray
            };
            stopButton.Click += async (s, e) =>
            {
                ((Button)s).IsEnabled = false;
                await Task.Run(() => group.Stop());
            };

            // 创建移除按钮
            var removeButton = new Button
            {
                Content = "移除",
                Padding = new Thickness(15, 5, 15, 5),
                Margin = new Thickness(5, 0, 0, 0),
                Height = 28,
                Background = Brushes.White,
                BorderBrush = Brushes.Gray
            };
            removeButton.Click += (s, e) =>
            {
                if (MessageBox.Show("确定要移除该转发组吗？", "确认", 
                    MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    group.Stop();
                    forwardGroups.Remove(group);
                    forwardGroupsPanel.Children.Remove(border);
                }
            };

            // 设置网格布局
            Grid.SetColumn(statusPanel, 0);
            Grid.SetColumn(stopButton, 1);
            Grid.SetColumn(removeButton, 2);

            grid.Children.Add(statusPanel);
            grid.Children.Add(stopButton);
            grid.Children.Add(removeButton);

            border.Child = grid;

            // 注册服务器1状态变化事件
            group.Server1StatusChanged += (s, status) =>
            {
                Dispatcher.Invoke(() => server1Status.Fill = status ? Brushes.Green : Brushes.Red);
            };

            // 注册服务器2状态变化事件
            group.Server2StatusChanged += (s, status) =>
            {
                Dispatcher.Invoke(() => server2Status.Fill = status ? Brushes.Green : Brushes.Red);
            };

            // 注册数据传输事件
            group.DataTransferred += (s, e) =>
            {
                Dispatcher.Invoke(() =>
                {
                    // 数据流指示灯闪烁效果
                    dataIndicator.Fill = Brushes.Yellow;
                    var timer = new System.Windows.Threading.DispatcherTimer
                    {
                        Interval = TimeSpan.FromMilliseconds(100)
                    };
                    timer.Tick += (s2, e2) =>
                    {
                        dataIndicator.Fill = Brushes.Gray;
                        timer.Stop();
                    };
                    timer.Start();
                });
            };

            return border;
        }
    }
}